import { Modal, Form, Input, Button, Space, message, Radio, Select } from 'antd'
import http from '../api/http'
import type { IEditmeals } from '../types/meals'
import type { FormInstance } from 'antd'
import { useEffect, useState } from 'react'


interface MealsType {
  id: number
  name: string
}

interface Props {
  EditModalOpen: boolean
  EditHandleCancel: () => void
  onSuccess: () => void
 
  editData?: IEditmeals
}

const Edit: React.FC<Props> = ({ EditModalOpen, EditHandleCancel, onSuccess, editData }) => {
  const [form] = Form.useForm<FormInstance<IEditmeals>>()
  const [SType, setType] = useState<Array<MealsType>>([])

  
  useEffect(() => {
    if (EditModalOpen) {
      http.get<Array<MealsType>>('MealsType')
        .then(res => setType(res.data))
        .catch(err => console.error('获取膳食类型失败:', err))
    }
   
  }, [EditModalOpen])

 
  useEffect(() => {
    if (editData) {
    
      form.setFieldsValue({
        code: editData.code,
        typeId: editData.typeId, 
        name: editData.name,
        energy: editData.energy,
        protein: editData.protein,
        fat: editData.fat,
        carbohydrate: editData.carbohydrate,
        kcal: editData.kcal,
        kj: editData.kj,
        explain: editData.explain,
        hbp: editData.hbp,
        diabetes: editData.diabetes,
        obesity: editData.obesity,
        hyperlipidemia: editData.hyperlipidemia,
        chd: editData.chd,
        stroke: editData.stroke,
        cacd: editData.cacd,
        ventilate: editData.ventilate
      })
    }
  }, [editData, form])

  
  const handleSubmit = () => {
    form.validateFields()
      .then(values => {
       
        if (!editData) {
          message.warning('未获取到待修改的膳食数据')
          return
        }

      
        const submitData = {
          ...values,
          id: editData.id
      
     
        }
        console.log(submitData)
        // 调用修改接口：PUT请求，URL拼接id
        http.put('Meals',submitData)
          .then(() => {
            message.success('修改成功')
            EditHandleCancel() // 关闭弹窗
            form.resetFields() // 重置表单
            onSuccess() // 通知父组件刷新列表
          })
          .catch(err => {
            console.error('修改失败:', err)
            message.error('修改失败，请重试')
          })
      })
      .catch(info => {
        console.log('表单验证失败:', info)
        message.warning('请完善必填字段')
       })
  }

  return (
    <Modal
      title="修改膳食" 
      open={EditModalOpen}
      onCancel={EditHandleCancel}
      centered
      footer={[
        <Button key="cancel" onClick={EditHandleCancel}>
          取消
        </Button>,
        <Button key="submit" type="primary" onClick={handleSubmit}>
          确认修改
        </Button>
      ]}
      destroyOnClose={true}
      width={600}
      
      disabled={!editData}
    >
      <Form
        form={form}
        layout="vertical"
       
        initialValues={{}}
      >
       
        <Form.Item
          name="code"
          label="编码"
          rules={[{ required: true, message: '请输入编码' }]}
        >
          <Input placeholder="请输入膳食编码" />
        </Form.Item>

        <Form.Item
          name="typeId"
          label="类型"
          rules={[{ required: true, message: '请选择类型' }]}
        >
          <Select placeholder="请选择类型" style={{ width: '100%' }}>
            {SType.map(n => (
              <Select.Option key={n.id} value={n.id}>
                {n.name}
              </Select.Option>
            ))}
          </Select>
        </Form.Item>

        <Form.Item
          name="name"
          label="膳食名称"
          rules={[{ required: true, message: '请输入膳食名称' }]}
        >
          <Input placeholder="请输入膳食名称" />
        </Form.Item>

        <Space style={{ width: '100%' }}>
          <Form.Item
            name="energy"
            label="100g含能量"
            rules={[{ required: true, message: '请输入能量值' }]}
            style={{ flex: 1 }}
          >
            <Input placeholder="单位：kcal" />
          </Form.Item>

          <Form.Item
            name="protein"
            label="蛋白质含量"
            rules={[{ required: true, message: '请输入蛋白质含量' }]}
            style={{ flex: 1 }}
          >
            <Input placeholder="单位：g" />
          </Form.Item>
        </Space>

        <Space style={{ width: '100%' }}>
          <Form.Item
            name="fat"
            label="脂肪含量"
            rules={[{ required: true, message: '请输入脂肪含量' }]}
            style={{ flex: 1 }}
          >
            <Input placeholder="单位：g" />
          </Form.Item>

          <Form.Item
            name="carbohydrate"
            label="碳水化合物含量"
            rules={[{ required: true, message: '请输入碳水化合物含量' }]}
            style={{ flex: 1 }}
          >
            <Input placeholder="单位：g" />
          </Form.Item>
        </Space>

        <Space style={{ width: '100%' }}>
          <Form.Item
            name="kcal"
            label="每kcal能量"
            rules={[{ required: true, message: '请输入每kcal能量' }]}
            style={{ flex: 1 }}
          >
            <Input />
          </Form.Item>

          <Form.Item
            name="kj"
            label="每kj能量"
            rules={[{ required: true, message: '请输入每kj能量' }]}
            style={{ flex: 1 }}
          >
            <Input />
          </Form.Item>
        </Space>

        <Form.Item
          name="explain"
          label="说明"
        >
          <Input.TextArea rows={3} placeholder="请输入膳食说明（可选）" />
        </Form.Item>

       
        <Space style={{ width: '100%', marginBottom: 16 }}>
          <Form.Item
            name="hbp"
            label="高血压"
            rules={[{ required: true, message: '请选择高血压适宜性' }]}
            style={{ flex: 1 }}
          >
            <Radio.Group>
              <Radio value={1}>适宜</Radio>
              <Radio value={0}>不适宜</Radio>
            </Radio.Group>
          </Form.Item>

          <Form.Item
            name="diabetes"
            label="糖尿病"
            rules={[{ required: true, message: '请选择糖尿病适宜性' }]}
            style={{ flex: 1 }}
          >
            <Radio.Group>
              <Radio value={1}>适宜</Radio>
              <Radio value={0}>不适宜</Radio>
            </Radio.Group>
          </Form.Item>
        </Space>

        <Space style={{ width: '100%' }}>
          <Form.Item
            name="obesity"
            label="肥胖"
            rules={[{ required: true, message: '请选择肥胖适宜性' }]}
            style={{ flex: 1 }}
          >
            <Radio.Group>
              <Radio value={1}>适宜</Radio>
              <Radio value={0}>不适宜</Radio>
            </Radio.Group>
          </Form.Item>

          <Form.Item
            name="hyperlipidemia"
            label="高血脂"
            rules={[{ required: true, message: '请选择高血脂适宜性' }]}
            style={{ flex: 1 }}
          >
            <Radio.Group>
              <Radio value={1}>适宜</Radio>
              <Radio value={0}>不适宜</Radio>
            </Radio.Group>
          </Form.Item>
        </Space>

        <Space style={{ width: '100%' }}>
          <Form.Item
            name="chd"
            label="冠心病"
            rules={[{ required: true, message: '请选择冠心病适宜性' }]}
            style={{ flex: 1 }}
          >
            <Radio.Group>
              <Radio value={1}>适宜</Radio>
              <Radio value={0}>不适宜</Radio>
            </Radio.Group>
          </Form.Item>

          <Form.Item
            name="stroke"
            label="脑卒中"
            rules={[{ required: true, message: '请选择脑卒中适宜性' }]}
            style={{ flex: 1 }}
          >
            <Radio.Group>
              <Radio value={1}>适宜</Radio>
              <Radio value={0}>不适宜</Radio>
            </Radio.Group>
          </Form.Item>
        </Space>

        <Space style={{ width: '100%' }}>
          <Form.Item
            name="cacd"
            label="心脑血管疾病"
            rules={[{ required: true, message: '请选择心脑血管疾病适宜性' }]}
            style={{ flex: 1 }}
          >
            <Radio.Group>
              <Radio value={1}>适宜</Radio>
              <Radio value={0}>不适宜</Radio>
            </Radio.Group>
          </Form.Item>

          <Form.Item
            name="ventilate"
            label="通风"
            rules={[{ required: true, message: '请选择通风适宜性' }]}
            style={{ flex: 1 }}
          >
            <Radio.Group>
              <Radio value={1}>适宜</Radio>
              <Radio value={0}>不适宜</Radio>
            </Radio.Group>
          </Form.Item>
        </Space>
      </Form>
    </Modal>
  )
}

export { Edit } 